import { ref } from 'vue'

import { catchFn } from '@/libs/common'
import { createQuiz, getQuizResult, sendQuizAnswer } from '../../api'
import { changeQuestion } from './api'
import { topMessage } from '@/components/TopMessage/data'

/** 测评类型Code */
const typeCode = 'anxiety'
/** 会话ID */
let sessionId = ''

/** 当前题目 */
const question = ref<T_Question>()
/** 当前选择 */
const selectIdx = ref(-1)
/** 焦虑抑郁测试结果 */
const result = ref<T_AnxietyResult>()

export { question, selectIdx, result }

const setSessionId = (id: string) => (sessionId = id)

/**
 * 更新测试结果
 */
const start = () =>
  catchFn(async () => {
    if (sessionId) {
      // 报告列表进入
      const { data } = await getQuizResult({ typeCode, sessionId })

      result.value = data.anxietyResult
    } else {
      // 正常进入
      const { data } = await createQuiz(typeCode)

      question.value = data.firstQuestion
      sessionId = data.sessionId
    }
  })

/**
 * 更新测试题
 */
const change = () =>
  catchFn(async () => {
    if (!sessionId || !question.value) return

    const { data } = await changeQuestion(sessionId, question.value.id)

    selectIdx.value = -1
    question.value = data
  })

/**
 * 获取测试结果
 */
const getResult = () =>
  catchFn(async () => {
    if (!question.value) return

    if (selectIdx.value === -1) {
      topMessage.warn('请选择一个答案')
      return
    }

    // 提交答案
    await sendQuizAnswer(
      sessionId,
      question.value.id,
      question.value.options[selectIdx.value].value,
    )

    // 查询结果
    const { data } = await getQuizResult({ typeCode, sessionId })

    result.value = data.anxietyResult
  })

/**
 * 清空
 */
const clear = () => {
  sessionId = ''
  selectIdx.value = -1
  question.value = undefined
  result.value = undefined
}

export { setSessionId, start, change, getResult, clear }
